<?php
class AuthPlugin extends Plugin
{
    private $auth;

    public function startup()
    {
        parent::startup();
        $this->auth = new Auth;
    }

    public function onEvent($type, $data)
    {
        if($type == 'presence' AND $data['type'] == 'available'){
            $attempt = 0;

            do {
                if(isset($data['xml']->subs[$attempt]->subs[0]->attrs['jid']))
                    $fullJid = $data['xml']->subs[$attempt]->subs[0]->attrs['jid'];

                $attempt++;

            }while(!isset($fullJid) AND $attempt < 10);
            
            if(!empty($fullJid)){

                list($jid, $resource) = explode('/', $fullJid);

                if(!$this->auth->isRegisterJid($jid)){
                    $this->auth->registerJid($jid, 'heslo');
                }
                $this->auth->registerLastNick($jid, $data['from']);
            }
        }
    }

    public function getMessage(Message $data)
    {
        if($data->jid === NULL){
            $auth = new Auth;
            $relativeJid = $auth->getJidFromLastNick( $data->getFrom() );
            if($relativeJid != NULL){
                $data->setJid($relativeJid);
            }
        }
        
        if($data->getType() == 'chat' AND preg_match('#^password ([^ ]+)$#i', $data->getBody(), $password)){
            $this->sendMessage('Heslo změneno na '.$password[1], $data->getFrom());
            $this->auth->changePassword($data->getJid(), $password[1]);
        }
    }
}
?>